const router = require('koa-router')()
const mongoose = require('mongoose')
const Image = mongoose.model('Image')
const stats = require('../helpers/stats')
const comments = require('../helpers/comments')

router.get('/', async (ctx, next) => {
    let num = await Image.count()
    if(num > 0)
    {
    await Promise.all([
        Image.find().sort({timestamp: -1}).limit(12),
        stats(),
        Image.find().sort({likes:-1}).limit(9),
        comments()
    ])
    .then(([images, stats, popular, comments]) => ctx.render('index',
          {images, stats, popular, comments}
      ))
    .catch(err => ctx.throw(500, err))
  } else{
      let images = []
      let pImages = []
      let stats = {images: 0,views: 0,likes: 0,comments: 0}
      let comments = []
      let popular = []
      await ctx.render('index',{images, stats, pImages, comments,popular})
  }
})

module.exports = router
